package parse

import (
	"Crawlab/common/engine/os"
	"Crawlab/common/model"
	"regexp"
	"strconv"
)

const (
	userRegexpTemplate         = `<h2 class="post-title"><a href="(http://localhost:8080/mock/album.zhenai.com/u/[0-9]+)">([^<]+)</a></h2>`
	userAgeRegexpTemplate      = `<td><span class="label">年龄：</span>([\d]+)岁</td>`
	userMarriageRegexpTemplate = `<td><span class="label">婚况：</span>([^<]+)</td>`
)

var userRegexp = regexp.MustCompile(userRegexpTemplate)
var userAgeRegexp = regexp.MustCompile(userAgeRegexpTemplate)
var userMarriageRegexp = regexp.MustCompile(userMarriageRegexpTemplate)

func UserParseResult(content []byte, name string) os.ParseResult {
	profile := model.Profile{}

	profile.Name = name

	age, err := strconv.Atoi(extractString(content, userAgeRegexp))
	if nil == err {
		profile.Age = age
	}

	profile.Marriage = extractString(content, userMarriageRegexp)

	result := os.ParseResult{Items: []interface{}{profile}}

	return result
}

func extractString(content []byte, regexp *regexp.Regexp) string {
	match := regexp.FindSubmatch(content)
	if len(match) >= 2 {
		return string(match[1])
	} else {
		return ""
	}

}
